module isdark;

import core.stdc.stdio;
import core.stdc.string;
import gamut;

ulong getBrightness(in char[] path) {
	Image image;
	image.loadFromFile(path);
	if (image.isError)
		return ulong.max;
	image.convertTo(PixelType.l16);
	if (!image.hasData)
		return ulong.max;
	ulong sum = 0;
	const width = image.width;
	const height = image.height;
	foreach (j; 0 .. height) {
		const line = cast(ushort[])image.scanline(j);
		foreach (i; 0 .. width) {
			const pixel = line[i];
			sum += pixel;
		}
	}
	return sum / (ulong(width) * height);
}

extern (C) int main(int argc, char** argv) {
	if (argc < 2) {
		fputs("Usage: isdark <image>\n", stderr);
		return 1;
	}
	const path = cast(string)argv[1][0 .. strlen(argv[1])];
	const brightness = getBrightness(path);
	if (brightness == ulong.max) {
		fputs("Error reading image\n", stderr);
		return 1;
	}
	printf(brightness > ushort.max / 2 ? "%3.2f%% 亮度：高\n" : "%3.2f%% 亮度：低\n",
		brightness / float(ushort.max) * 100);
	return 0;
}
